<?php

class UsersController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
    	 public function filters()
	{
		return array(
			'accessControl',
		);
	}

	public function accessRules()
	{
		return array(
			array('allow',
			      'actions' => array('login'),
			      'users' => array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('add','index','edit','delete'),
				'roles'=>array('admin'),
			),
			array('deny',
			      'users' => array('*'),
			),
		);
	}

	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	public function actionIndex()
	{
		$this->pagetitle = 'Пользователи - '.Yii::app()->name;
		$criteria = new CDbCriteria;
        $criteria->condition = "role='user'";
		//$criteria->order = 'date_public DESC';
		$model = Users::model()->findAll($criteria);
		$this->render('index', array('model'=>$model));
	}



    public function actionEdit($id)
    {
        $model = Users::model()->findByPk($id);
        if(isset($_POST['Users']))
        {
            $model->attributes = $_POST['Users'];
            $model->password = md5(md5($model->password));
            if($model->validate())
            {
                $model->save();
                $this->redirect(array('/users'));
            }
        }
        $this->render('form', array('model' => $model));

    }

    public function actionAdd()
    {
        $model = new Users;
        if(isset($_POST['Users']))
        {
            $model->attributes = $_POST['Users'];
            $model->role = 'user';
            $model->password = md5(md5($model->password));
            if($model->validate())
            {
                $model->save();
                $this->redirect(array('/users'));
            }
        }
        $this->render('aform', array('model' => $model));
    }

    public function actionDelete($id)
    {
        Users::model()->deleteByPk($id);
        $this->redirect(array('/users'));
    }


    private function uniqueName($fname)
	{
		$ext = end(explode(".",$fname));
		return md5(uniqid()).'.'.$ext;
	}


}